package com.xsq.wifi.utils;

import android.content.Context;
import android.graphics.*;
import android.os.Build;
import androidx.annotation.NonNull;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import java.security.MessageDigest;

/**
 * 编写人：李振德
 * 创建时间：2025/5/20
 */

public class RoundedCornersTransformation extends BitmapTransformation {
    private final float radius; // 单位：px

    public RoundedCornersTransformation(Context context, int dpRadius) {
        this.radius = dpToPx(context, dpRadius);
    }

    @Override
    protected Bitmap transform(
            @NonNull BitmapPool pool,
            @NonNull Bitmap toTransform,
            int outWidth,
            int outHeight
    ) {
        Bitmap output = Bitmap.createBitmap(
                toTransform.getWidth(),
                toTransform.getHeight(),
                Bitmap.Config.ARGB_8888
        );

        Canvas canvas = new Canvas(output);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        RectF rect = new RectF(0, 0, toTransform.getWidth(), toTransform.getHeight());

        // 绘制圆角矩形
        canvas.drawRoundRect(rect, radius, radius, paint);

        // 应用源图像
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(toTransform, 0, 0, paint);

        return output;
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
        messageDigest.update(("RoundedCornersTransformation(" + radius + ")").getBytes());
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof RoundedCornersTransformation
                && ((RoundedCornersTransformation) o).radius == radius;
    }

    @Override
    public int hashCode() {
        return ("RoundedCornersTransformation(" + radius + ")").hashCode();
    }

    // dp转px
    private float dpToPx(Context context, int dp) {
        return dp * context.getResources().getDisplayMetrics().density;
    }
}